<template>
  <div class="login-containerWrap">
    <div class="login-container">
      <el-form
        ref="loginForm"
        label-width="60px"
        class="login-form"
        :rules="rules"
        :model="loginForm"
      >
        <h2 class="login-title">xx会员管理系统-登录</h2>
        <el-form-item label="账号" prop="username" style="width:320px">
          <el-input
            placeholder="请输入帐号"
            v-model="loginForm.username"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
          style="width:320px;margin-bottom:17px"
        >
          <el-input
            type="password"
            placeholder="请输入密码"
            v-model="loginForm.password"
            show-password
          ></el-input>
        </el-form-item>

        <el-form-item style="margin:0">
          <el-checkbox
            label="七天免登陆"
            name="type"
            v-model="loginForm.keep"
          ></el-checkbox>
        </el-form-item>

        <el-form-item style="margin:0;">
          <el-button type="primary" @click="$router.push('/reg')"
            >注册</el-button
          >
          <el-button
            type="primary"
            @click="goLogin('loginForm')"
            style="margin-left:120px"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import userApi from "@/api/userApi.js";
import { setToken, setUser } from "@/utils/auth.js";
export default {
  name: "Login",
  data() {
    let usernameRule = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    };
    let passwordRule = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    return {
      name: "Login",
      loginForm: {
        username: "",
        password: "",
        keep: ""
      },
      // 表单验证
      rules: {
        username: [{ validator: usernameRule, trigger: "change" }],
        password: [{ validator: passwordRule, trigger: "change" }]
      }
    };
  },
  methods: {
    // 功能：登录
    goLogin(formName) {
      this.$refs[formName].validate(valid => {
        // 判断是否通过表单验证
        if (valid) {
          // 对密码进行md5加密
          let encryptPassword = this.$md5(this.loginForm.password);
          // 检验通过发送请求
          userApi
            .login(this.loginForm.username, encryptPassword)
            .then(res => {
              if (res.data.code) {
                // 登录成功消息提示
                this.$message({
                  showClose: true,
                  message: res.data.message,
                  type: "success",
                  duration: 2000
                });
                // 将token存到本地存储,判断是否需要储存7天
                if (this.loginForm.keep) {
                  // 保存7天
                  setToken(res.data.token, 7);
                  setUser(this.loginForm.username, 7);
                } else {
                  //会话级别:关掉浏览器就没有了
                  setToken(res.data.token);
                  setUser(this.loginForm.username);
                }
                // 跳转
                this.$router.push({
                  path: "/home"
                });
              } else {
                // 登录失败，消息提示
                this.$message({
                  showClose: true,
                  message: res.data.message,
                  type: "error",
                  duration: 2000
                });
                // 登录失败,清空密码输入框数据
                this.$refs.loginForm.resetFields();
              }
            })
            .catch(err => {
              console.log("出错了", err);
            });
        } else {
          console.log("表单校验错误");
        }
      });
    }
  },

  components: {},
  created() {
    // 从注册页面过来的，直接显示刚刚注册过的用户名；
    this.loginForm.username = this.$route.query.username;
  }
};
</script>

<style scoped lang='scss'>
.login-container {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  background: url("/img/background.jpg") no-repeat;
  background-size: 100% 100%;
  overflow: hidden;
  display: flex;
  .login-form {
    width: 350px;
    margin: auto;
    background-color: rgb(255, 255, 255, 0.3);
    padding: 30px;
    border-radius: 20px;
    .login-title {
      text-align: center;
      padding-bottom: 20px;
      color: #303133;
    }
  }
}
</style>